package com.by.wx.ctrl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.by.wx.factory.MessageProcessFactory;
import com.by.wx.mapper.FlightInfoMapper;
import com.by.wx.mapper.FlightRecordLogMapper;
import com.by.wx.model.msg.FlightInfo;
import com.by.wx.model.msg.FlightRecordLog;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * @Author 陈子杰
 * @Description 接受消息Controller
 * @Version 1.0.0
 * @Date 2025/1/1 18:57
 */
@Slf4j
@RequestMapping("message")
@RestController
@RequiredArgsConstructor
public class MessageCtrl {
    private final MessageProcessFactory messageProcessFactory;
    private final FlightInfoMapper flightInfoMapper;
    private final FlightRecordLogMapper flightRecordLogMapper;

    @Value("${feishu.url}")
    private String url;

    /**
     * 登录异常
     *
     * @param deviceName 设备名
     */
    @GetMapping("loginError")
    public void loginError(@RequestParam("deviceName") String deviceName) {
        if (StrUtil.isNotBlank(deviceName)) {
            Map<String, Object> body = new HashMap<>();
            body.put("msg_type", "text");
            Map<String, Object> innerMap = new HashMap<>();
            String msg = String.format("设备：%s，登录失败！！！", deviceName);
            innerMap.put("text", msg);
            body.put("content", innerMap);
            HttpUtil.post(url, JSON.toJSONString(body));
        }
    }

    /**
     * 记录日志
     *
     * @param recordLog 航班运行日志表
     */
    @PostMapping("recordLog")
    public void recordLog(@RequestBody FlightRecordLog recordLog) {
        LambdaQueryWrapper<FlightRecordLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlightRecordLog::getDeviceName, recordLog.getDeviceName());
        queryWrapper.eq(FlightRecordLog::getType, recordLog.getType());
        FlightRecordLog log = flightRecordLogMapper.selectOne(queryWrapper);
        recordLog.setLastTime(LocalDateTime.now());
        if (ObjectUtil.isEmpty(log)) {
            flightRecordLogMapper.insert(recordLog);
        } else {
            log.setLastTime(LocalDateTime.now());
            flightRecordLogMapper.updateById(log);
        }
    }

    @PostMapping("receptionTicketsLeft")
    public void receptionTicketsLeft(@RequestBody FlightInfo dto) {
        int year = LocalDate.now().getYear();
        LocalDate date = LocalDate.of(year, Integer.parseInt(dto.getMonth()), Integer.parseInt(dto.getDay()));
        date.format(DateTimeFormatter.ISO_LOCAL_DATE);
        dto.setDate(date.toString());
        LambdaQueryWrapper<FlightInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FlightInfo::getDate, dto.getDate());
        queryWrapper.eq(FlightInfo::getStartCity, dto.getStartCity());
        queryWrapper.eq(FlightInfo::getEndCity, dto.getEndCity());
        queryWrapper.eq(FlightInfo::getFlightNo, dto.getFlightNo());
        queryWrapper.eq(FlightInfo::getCabin, dto.getCabin());
        List<FlightInfo> infos = flightInfoMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(infos)) {
            for (FlightInfo info : infos) {
                if (StrUtil.isBlank(info.getRemain()) || !info.getRemain().equals(dto.getRemain())) {
                    info.setRemain(dto.getRemain());
                    Map<String, Object> body = new HashMap<>();
                    body.put("msg_type", "text");
                    Map<String, Object> innerMap = new HashMap<>();
                    String msg = String.format("%s-%s，航班号：%s，舱位：%s，余票数量：%s", info.getStartCity(), info.getEndCity(), info.getFlightNo(), info.getCabin(), info.getRemain());
                    innerMap.put("text", msg);
                    body.put("content", innerMap);
                    HttpUtil.post(url, JSON.toJSONString(body));
                    flightInfoMapper.updateById(info);
                }
            }
        }
    }

    @GetMapping("getFlightInfo")
    public List<Object[]> getFlightInfo() {
        List<FlightInfo> infos = flightInfoMapper.selectList(null);
        List<Object[]> infoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(infos)) {
            infoList = infos.stream().map(info -> {
                LocalDate date = LocalDate.parse(info.getDate(), DateTimeFormatter.ISO_LOCAL_DATE);
                return new Object[]{"1231313", "1231313", info.getStartCity(), info.getEndCity(), date.getMonthValue(), date.getDayOfMonth(), info.getFlightNo(), info.getCabin()};
            }).collect(Collectors.toList());
        }
        log.info("infoList：{}", JSON.toJSONString(infoList));
        return infoList;
    }

    @PostMapping("addMonitoring")
    public String addMonitoring(HttpServletRequest request) throws IOException {
        BufferedReader reader = request.getReader();
        StringBuilder requestBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            requestBody.append(line);
        }
        // 得到原始 JSON 字符串
        String jsonStr = requestBody.toString();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String id = jsonObject.getString("id");
        String val = jsonObject.getString("val");
        String datePattern = "日期：(.*)";
        String departurePattern = "起飞：(.*)";
        String arrivalPattern = "到达：(.*)";
        String flightNumberPattern = "航班号：(.*)";
        String cabinPattern = "舱位：(.*)";
        FlightInfo flightInfo = new FlightInfo();
        flightInfo.setGroupName(id);
        flightInfo.setDate(extractValue(val, datePattern));
        flightInfo.setStartCity(extractValue(val, departurePattern));
        flightInfo.setEndCity(extractValue(val, arrivalPattern));
        flightInfo.setFlightNo(extractValue(val, flightNumberPattern));
        flightInfo.setCabin(extractValue(val, cabinPattern));
        flightInfo.setRegisterDate(LocalDate.now().toString());
        flightInfo.setExpireDate(LocalDate.now().plusDays(15L).toString());
        flightInfo.setCreateTime(LocalDateTime.now());
        flightInfoMapper.insert(flightInfo);
        return "{\"msg\":\"success\"}";
    }

    private static String extractValue(String text, String pattern) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(text);
        return m.find() ? m.group(1) : "";
    }
}
